<template>
  <module :code-str="codeStr" :code-desc="codeDesc">
    <template #moduleName>头像上传组件demo</template>
    <template #moduleDesc></template>
    <template #moduleComponent>
      <h-container class="com-cropper-container" fluid>
        <h-container justify="center">
          <h-aside class="com-cropper-panel" gutter justify="start">
            <h-cropper
              ref="cropper"
              class="com-cropper-wrap"
              :img="cropImg"
              :fixedNumber="[5, 7]"
              @realTime="onRealTime"
            ></h-cropper>
          </h-aside>
          <h-aside class="com-preview-panel" gutter justify="start">
            <div ref="preview" class="com-preview-wrap">
              <div class="com-preview-div" :style="previewDiv">
                <img v-bind="previewImg" />
              </div>
            </div>
            <div class="c-cropper-action">
              <h-upload
                ref="upload"
                :show-file-list="false"
                :on-change="onUploaded"
              ></h-upload>
            </div>
          </h-aside>
        </h-container>
        <h-footer gutter border justify="center">
          <h-button size="small" @click="onCancel">取消</h-button>
          <h-button size="small" type="primary" @click="onConfirm"
            >确认</h-button
          >
        </h-footer>
      </h-container>
    </template>
  </module>
</template>

<script>
export default {
  inject: {
    emitModal: {
      default: () => function () {},
    },
    closeModal: {
      default: () => function () {},
    },
  },
  alias: "V1CropperHeadImageUploadDemo",
  data() {
    return {
      file: null,
      cropImg: null,
      preview: {
        w: 0,
        h: 0,
        url: "",
      },
      codeStr: `
<template>
  <h-container class="com-cropper-container" fluid>
    <h-container justify="center">
      <h-aside class="com-cropper-panel" gutter justify="start">
        <h-cropper
            ref="cropper"
            class="com-cropper-wrap"
            :img="cropImg"
            :fixedNumber="[5, 7]"
            @realTime="onRealTime"></h-cropper>
      </h-aside>
      <h-aside class="com-preview-panel" gutter justify="start">
        <div ref="preview" class="com-preview-wrap">
          <div class="com-preview-div" :style="previewDiv">
            <img v-bind="previewImg"/>
          </div>
        </div>
        <div class="c-cropper-action">
          <h-upload ref="upload" :show-file-list="false" :on-change="onUploaded"></h-upload>
        </div>
      </h-aside>
    </h-container>
    <h-footer gutter border justify="center">
      <h-button size="small" @click="onCancel">取消</h-button>
      <h-button size="small" type="primary" @click="onConfirm">确认</h-button>
    </h-footer>
  </h-container>
</template>

<script>
export default {
  inject: {
    emitModal: {
      default: () => function () {
      }
    },
    closeModal: {
      default: () => function () {
      }
    }
  },
  data() {
    return {
      file: null,
      cropImg: null,
      preview: {
        w: 0,
        h: 0,
        url: '',
      },
    }
  },
  computed: {
    previewDiv() {
      const wrapWidth = this.$refs.preview ? this.$refs.preview.offsetWidth : 0
      const wrapHeight = this.$refs.preview ? this.$refs.preview.offsetHeight : 0

      let zoom = wrapWidth / this.preview.w
      if ((wrapWidth / this.preview.w) > (wrapHeight / this.preview.h)) {
        zoom = wrapHeight / this.preview.h
      }

      return {
        ...this.preview.div,
        zoom: zoom
      }
    },
    previewImg() {
      return {
        src: this.preview.url,
        style: this.preview.img
      }
    }
  },
  methods: {
    onUploaded(file) {
      if (!/\.(jpg|jpeg|png|bmp|JPG|PNG|BMP)$/.test(file.name)) {
        this.$message.error('图片类型要求：jpeg、jpg、png、bmp')
        return false
      }

      this.file = file.raw

      //转化为blob
      let reader = new FileReader()
      reader.onload = (e) => {
        let data
        if ((typeof e.target.result) === 'object') {
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        this.cropImg = data
      }
      //转化为base64
      reader.readAsDataURL(file.raw)

      this.$refs.upload.clearFiles()
    },
    onRealTime(data) {
      this.preview = data
    },
    onCancel() {
      this.closeModal()
    },
    onConfirm() {
      const cropDataPromise = this.$refs.cropper.getCropData()
      const cropBlobPromise = this.$refs.cropper.getCropBlob()

      Promise.all([cropDataPromise, cropBlobPromise]).then(results => {
        this.closeModal()
        this.$emit('confirm', {data: results[0], blob: results[1], original: this.file})
      }).catch(() => {
        this.$message.error('请先上传图片进行剪裁！')
      })
    }
  }
}
<\/script>

<style scoped lang="scss">
.com-cropper-container {
  .com-cropper-panel {

    .com-cropper-wrap {
      position: relative;
      width: 20em;
      height: 20em;
      overflow: hidden;
    }
  }

  .com-preview-panel {

    .com-preview-wrap {
      position: relative;
      width: 10em;
      height: 14em;
      overflow: hidden;
      background: url();
    }
  }

  .c-cropper-action {
    margin-top: 1em;
  }
}
<\/style>

      `,
      codeDesc: "",
    }
  },
  computed: {
    previewDiv() {
      const wrapWidth = this.$refs.preview ? this.$refs.preview.offsetWidth : 0;
      const wrapHeight = this.$refs.preview
        ? this.$refs.preview.offsetHeight
        : 0;

      let zoom = wrapWidth / this.preview.w;
      if (wrapWidth / this.preview.w > wrapHeight / this.preview.h) {
        zoom = wrapHeight / this.preview.h;
      }

      return {
        ...this.preview.div,
        zoom: zoom,
      };
    },
    previewImg() {
      return {
        src: this.preview.url,
        style: this.preview.img,
      };
    },
  },
  methods: {
    onUploaded(file) {
      if (!/\.(jpg|jpeg|png|bmp|JPG|PNG|BMP)$/.test(file.name)) {
        this.$message.error("图片类型要求：jpeg、jpg、png、bmp");
        return false;
      }

      this.file = file.raw;

      //转化为blob
      let reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropImg = data;
      };
      //转化为base64
      reader.readAsDataURL(file.raw);

      this.$refs.upload.clearFiles();
    },
    onRealTime(data) {
      this.preview = data;
    },
    onCancel() {
      this.closeModal();
    },
    onConfirm() {
      const cropDataPromise = this.$refs.cropper.getCropData();
      const cropBlobPromise = this.$refs.cropper.getCropBlob();

      Promise.all([cropDataPromise, cropBlobPromise])
        .then((results) => {
          this.closeModal();
          this.$emit("confirm", {
            data: results[0],
            blob: results[1],
            original: this.file,
          });
        })
        .catch(() => {
          this.$message.error("请先上传图片进行剪裁！");
        });
    },
  },
};
</script>

<style scoped lang="scss">
.com-cropper-container {
  .com-cropper-panel {
    .com-cropper-wrap {
      position: relative;
      width: 20em;
      height: 20em;
      overflow: hidden;
    }
  }

  .com-preview-panel {
    .com-preview-wrap {
      position: relative;
      width: 10em;
      height: 14em;
      overflow: hidden;
      background: url();
    }
  }

  .c-cropper-action {
    margin-top: 1em;
  }
}
</style>
